package us.proyecto.canarios.actions.concursos;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.jooreports.templates.DocumentTemplateException;
import net.sf.jooreports.templates.UnzippedDocumentTemplate;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.FlushModeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.datamodel.DataModelSelection;
import org.jboss.seam.faces.FacesMessages;

import org.jboss.seam.log.Log;

import us.proyecto.canarios.dao.ConcursoDAO;
import us.proyecto.canarios.dao.PajarosDAO;
import us.proyecto.canarios.domain.Concurso;
import us.proyecto.canarios.domain.Criador;
import us.proyecto.canarios.domain.Puntuacion;
import us.proyecto.canarios.domain.PuntuacionGrupo;
import us.proyecto.canarios.domain.Usuario;

import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.DocumentFormatRegistry;
import com.artofsolving.jodconverter.XmlDocumentFormatRegistry;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.Encoder;
import com.google.zxing.qrcode.encoder.QRCode;

@Name("gestionConcursoCriador")
@Scope(ScopeType.SESSION)
public class GestionConcursoCriadorAction {

	@Logger
	Log log;

	@In
	private Usuario user;

	private Concurso concurso;

	private Criador criador;

	@DataModel("listaPajarosIndividualCriador")
	private List<Puntuacion> listaPajarosIndividual;
	@DataModelSelection("listaPajarosIndividualCriador")
	private Puntuacion puntuacion;

	@DataModel("listaGrupoCriador")
	private List<PuntuacionGrupo> listaGrupo;
	@DataModelSelection("listaGrupoCriador")
	private PuntuacionGrupo puntuacionGrupo;
	
	

	@In(create = true)
	private ConcursoDAO concursoDAO;

	@In(create = true)
	private PajarosDAO pajarosDAO;

	@Begin(join = true, flushMode=FlushModeType.MANUAL)
	public String gestion(Concurso con) {
	//	createQrCode(150,150);
		if (con.getIdConcurso() != 0) {
			concurso = con;
			criador = user.getCriador();
			listaGrupo = pajarosDAO.getListaGruposXConcurso(con, criador);
			for(PuntuacionGrupo g: listaGrupo){
				if(g.getPuntuaciones()!= null && g.getPuntuaciones().size()>0){
					for(Puntuacion p: g.getPuntuaciones()){
						g.setTipo(p.getPajaro().getTipo().getNombre());
					}
				}
			} 
			listaPajarosIndividual = pajarosDAO.getListaPajarosXConcursoTodos(con, criador);
			criador = null;
			return "true";
		}
		return "false";
	}

	/*public void buscar() {
		if (criador != null) {
			listaPajarosIndividual = pajarosDAO.getListaPajarosXConcurso(
					concurso, criador);
			listaGrupo = pajarosDAO.getListaGruposXConcurso(concurso, criador);
			if (listaGrupo != null) {
				for (PuntuacionGrupo pun : listaGrupo) {
					if (pun.getPuntuaciones() != null
							&& pun.getPuntuaciones().size() > 0) {
						for (Puntuacion p : pun.getPuntuaciones()) {
							pun.setCriador(p.getPajaro().getCriador()
									.getNumCriador());
							pun.setTipo(p.getPajaro().getTipo().getNombre());
						}
					}
				}
			}
		}
	}*/
	
	public int generarHojaInscripcionInd(){
		Map<String, Object> map = new HashMap<String, Object>();

        URL uri = this.getClass().getClassLoader().getResource("plantillas/Hoja inscripcion individual");

        File c = null;
        try {
            c = new File(uri.toURI());
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }

        	UnzippedDocumentTemplate t = new UnzippedDocumentTemplate(c);
            map.put("listaPuntuaciones", listaPajarosIndividual);
            map.put("criador", criador);
            map.put("concurso", concurso);
            
            if(listaPajarosIndividual != null && concurso.getPrecio() != null){
            	BigDecimal bd = new BigDecimal(listaPajarosIndividual.size()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            	bd = bd.multiply(concurso.getPrecio()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            	map.put("numEjemplares", listaPajarosIndividual.size());
            	map.put("precioTotal", bd.toString().replaceAll("\\.", ","));
            }
            
            map.put("localidad", concurso.getMunicipio().getNombre());
            Calendar cal = new GregorianCalendar();
            map.put("dia", cal.get(Calendar.DAY_OF_MONTH));
            map.put("mes", cal.get(Calendar.MONTH));
            map.put("anio", cal.get(Calendar.YEAR));

            try {

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                t.createDocument(map, out);

                byte[] b = out.toByteArray();

                // connect to an OpenOffice.org instance running on port 8100
                String host = ResourceBundle.getBundle("openoffice").getString("host");
                int port = Integer.parseInt(ResourceBundle.getBundle("openoffice").getString("port"));
                OpenOfficeConnection connection = new SocketOpenOfficeConnection(host, port);
                connection.connect();

                // convert
                DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);

                DocumentFormatRegistry registry = new  DefaultDocumentFormatRegistry();
                DocumentFormat odt = registry.getFormatByFileExtension("odt");
                DocumentFormat pdf = registry.getFormatByFileExtension("pdf");

                ByteArrayOutputStream outpdf = new ByteArrayOutputStream();

                ByteArrayInputStream in = new ByteArrayInputStream(b);
                converter.convert(in, odt, outpdf, pdf);
                byte[] bpdf = outpdf.toByteArray();

                connection.disconnect();

                FacesContext faces = FacesContext.getCurrentInstance();
                HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse();

                String odtname = "\"" + "Hoja inscripcion individual.pdf\"";
                response.setContentType("application/pdf");
                response.setContentLength(bpdf.length);
                response.setHeader("Content-disposition", "attachment; filename=" + odtname);

                ServletOutputStream desc = response.getOutputStream();
                desc.write(bpdf);

                faces.responseComplete();

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                System.out.println("No se puede abrir el archivo");
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println("Error de I/O");
                e.printStackTrace();
            } catch (DocumentTemplateException e) {
                // TODO Auto-generated catch block
                System.out.println("Error en la plantilla");
                e.printStackTrace();
            }
       
        return 0;
	}
	
	public int generarHojaInscripcionEquipo(){
		Map<String, Object> map = new HashMap<String, Object>();

        URL uri = this.getClass().getClassLoader().getResource("plantillas/Hoja inscripcion equipo");

        File c = null;
        try {
            c = new File(uri.toURI());
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }

        	UnzippedDocumentTemplate t = new UnzippedDocumentTemplate(c);
            map.put("listaPuntuacionGrupo", listaGrupo);
            map.put("criador", criador);
            map.put("concurso", concurso);
            
            int contador = 0;
            for(PuntuacionGrupo pg : listaGrupo){
            	int cont = 1;
            	for(Puntuacion p:pg.getPuntuaciones()){
            		contador++;
            		if(cont == 1){
            			pg.setPuntuacion1(p);
            		}else if(cont == 2){
            			pg.setPuntuacion2(p);
            		}else if(cont == 3){
            			pg.setPuntuacion3(p);
            		}else if(cont == 4){
            			pg.setPuntuacion4(p);
            		}
            		cont++;
            	}
            }
            
            
            if(listaGrupo != null && concurso.getPrecio() != null){
            	BigDecimal bd = new BigDecimal(contador).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            	bd = bd.multiply(concurso.getPrecio()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            	map.put("numEjemplares", contador);
            	map.put("precioTotal", bd.toString().replaceAll("\\.", ","));
            }
            
            map.put("localidad", concurso.getMunicipio().getNombre());
            Calendar cal = new GregorianCalendar();
            map.put("dia", cal.get(Calendar.DAY_OF_MONTH));
            map.put("mes", cal.get(Calendar.MONTH));
            map.put("anio", cal.get(Calendar.YEAR));

            try {

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                t.createDocument(map, out);

                byte[] b = out.toByteArray();

                // connect to an OpenOffice.org instance running on port 8100
                String host = ResourceBundle.getBundle("openoffice").getString("host");
                int port = Integer.parseInt(ResourceBundle.getBundle("openoffice").getString("port"));
                OpenOfficeConnection connection = new SocketOpenOfficeConnection(host, port);
                connection.connect();

                // convert
                DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);

                DocumentFormatRegistry registry = new  DefaultDocumentFormatRegistry();
                DocumentFormat odt = registry.getFormatByFileExtension("odt");
                DocumentFormat pdf = registry.getFormatByFileExtension("pdf");

                ByteArrayOutputStream outpdf = new ByteArrayOutputStream();

                ByteArrayInputStream in = new ByteArrayInputStream(b);
                converter.convert(in, odt, outpdf, pdf);
                byte[] bpdf = outpdf.toByteArray();

                connection.disconnect();

                FacesContext faces = FacesContext.getCurrentInstance();
                HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse();

                String odtname = "\"" + "Hoja inscripcion individual.pdf\"";
                response.setContentType("application/pdf");
                response.setContentLength(bpdf.length);
                response.setHeader("Content-disposition", "attachment; filename=" + odtname);

                ServletOutputStream desc = response.getOutputStream();
                desc.write(bpdf);

                faces.responseComplete();

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                System.out.println("No se puede abrir el archivo");
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println("Error de I/O");
                e.printStackTrace();
            } catch (DocumentTemplateException e) {
                // TODO Auto-generated catch block
                System.out.println("Error en la plantilla");
                e.printStackTrace();
            }
       
        return 0;
	}
	
	public int generarEtiqueta(){
		 Map<String, Object> map = new HashMap<String, Object>();

	        URL uri = this.getClass().getClassLoader().getResource("plantillas/ETIQUETAS");

	        File c = null;
	        try {
	            c = new File(uri.toURI());
	        } catch (URISyntaxException e1) {
	            e1.printStackTrace();
	        }

	        	UnzippedDocumentTemplate t = new UnzippedDocumentTemplate(c);
	            map.put("puntuacion", puntuacion);

	            createQrCode(150,150);
	            try {

	                ByteArrayOutputStream out = new ByteArrayOutputStream();
	                t.createDocument(map, out);

	                byte[] b = out.toByteArray();

	                // connect to an OpenOffice.org instance running on port 8100
	                String host = ResourceBundle.getBundle("openoffice").getString("host");
	                int port = Integer.parseInt(ResourceBundle.getBundle("openoffice").getString("port"));
	                OpenOfficeConnection connection = new SocketOpenOfficeConnection(host, port);
	                connection.connect();

	                // convert
	                DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);

	                DocumentFormatRegistry registry = new  DefaultDocumentFormatRegistry();
	                DocumentFormat odt = registry.getFormatByFileExtension("odt");
	                DocumentFormat pdf = registry.getFormatByFileExtension("pdf");

	                ByteArrayOutputStream outpdf = new ByteArrayOutputStream();

	                ByteArrayInputStream in = new ByteArrayInputStream(b);
	                converter.convert(in, odt, outpdf, pdf);
	                byte[] bpdf = outpdf.toByteArray();

	                connection.disconnect();

	                FacesContext faces = FacesContext.getCurrentInstance();
	                HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse();

	                String odtname = "\"" + "etiqueta.pdf\"";
	                response.setContentType("application/pdf");
	                response.setContentLength(bpdf.length);
	                response.setHeader("Content-disposition", "attachment; filename=" + odtname);

	                ServletOutputStream desc = response.getOutputStream();
	                desc.write(bpdf);

	                faces.responseComplete();

	            } catch (FileNotFoundException e) {
	                // TODO Auto-generated catch block
	                System.out.println("No se puede abrir el archivo");
	                e.printStackTrace();
	            } catch (IOException e) {
	                // TODO Auto-generated catch block
	                System.out.println("Error de I/O");
	                e.printStackTrace();
	            } catch (DocumentTemplateException e) {
	                // TODO Auto-generated catch block
	                System.out.println("Error en la plantilla");
	                e.printStackTrace();
	            }
	       
	        return 0;
	}
	public int generarEtiquetaGrupo(){
		 Map<String, Object> map = new HashMap<String, Object>();

	        URL uri = this.getClass().getClassLoader().getResource("plantillas/EtiquetasGrupo");

	        File c = null;
	        try {
	            c = new File(uri.toURI());
	        } catch (URISyntaxException e1) {
	            e1.printStackTrace();
	        }

	        	UnzippedDocumentTemplate t = new UnzippedDocumentTemplate(c);
	        	int i = 1;
	        	for(Puntuacion p : puntuacionGrupo.getPuntuaciones()){
	        		map.put("puntuacion"+i, p);
	        		createQrCodeGrupo(150,150,i,p);
	        		i++;
	        	}
	        	

	            try {

	                ByteArrayOutputStream out = new ByteArrayOutputStream();
	                t.createDocument(map, out);

	                byte[] b = out.toByteArray();

	                // connect to an OpenOffice.org instance running on port 8100
	                String host = ResourceBundle.getBundle("openoffice").getString("host");
	                int port = Integer.parseInt(ResourceBundle.getBundle("openoffice").getString("port"));
	                OpenOfficeConnection connection = new SocketOpenOfficeConnection(host, port);
	                connection.connect();

	                // convert
	                DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);

	                DocumentFormatRegistry registry = new  DefaultDocumentFormatRegistry();
	                DocumentFormat odt = registry.getFormatByFileExtension("odt");
	                DocumentFormat pdf = registry.getFormatByFileExtension("pdf");

	                ByteArrayOutputStream outpdf = new ByteArrayOutputStream();

	                ByteArrayInputStream in = new ByteArrayInputStream(b);
	                converter.convert(in, odt, outpdf, pdf);
	                byte[] bpdf = outpdf.toByteArray();

	                connection.disconnect();

	                FacesContext faces = FacesContext.getCurrentInstance();
	                HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse();

	                String odtname = "\"" + "etiquetasGrupo.pdf\"";
	                response.setContentType("application/pdf");
	                response.setContentLength(bpdf.length);
	                response.setHeader("Content-disposition", "attachment; filename=" + odtname);

	                ServletOutputStream desc = response.getOutputStream();
	                desc.write(bpdf);

	                faces.responseComplete();

	            } catch (FileNotFoundException e) {
	                // TODO Auto-generated catch block
	                System.out.println("No se puede abrir el archivo");
	                e.printStackTrace();
	            } catch (IOException e) {
	                // TODO Auto-generated catch block
	                System.out.println("Error de I/O");
	                e.printStackTrace();
	            } catch (DocumentTemplateException e) {
	                // TODO Auto-generated catch block
	                System.out.println("Error en la plantilla");
	                e.printStackTrace();
	            }
	       
	        return 0;
	}

	
	public void createQrCodeGrupo(int width,int heigth, int in, Puntuacion p) {
		try {
			byte[] b = { 0x48, 0x45, 0x4C, 0x4C, 0x4F };
			// convert the byte array into a UTF-8 string
			String data;
			data = new String(b, "UTF8");

			QRCode qrcode = new QRCode();
			Encoder.encode("http://localhost:8080/Canarios/consultaPajaro.html?id="+p.getIdPuntuacion(), ErrorCorrectionLevel.L,
					qrcode);

			int qrSize = qrcode.getMatrixWidth();

			int margin = 4;
			int imageSize = qrSize + 2 * margin; // includes quiet zone
			if (width < imageSize)
				width = imageSize;
			int magnify = width / imageSize;
			int remaining = width % imageSize;
			int topLeftPosition = ((remaining > 0) ? remaining / 2 : magnify)
					+ margin * magnify;
			int size = width;

			// Make the BufferedImage that are to hold the QRCode
			BufferedImage image = new BufferedImage(size, size,
					BufferedImage.TYPE_INT_RGB);
			image.createGraphics();
			Graphics2D graphics = (Graphics2D) image.getGraphics();
			graphics.setColor(Color.WHITE);
			graphics.fillRect(0, 0, size, size);

			// paint the image using the ByteMatrix
			graphics.setColor(Color.BLACK);
			for (int i = 0; i < qrSize; i++) {
				for (int j = 0; j < qrSize; j++) {
					if (qrcode.at(i, j) == 1)
						graphics.fillRect(topLeftPosition + i * magnify,
								topLeftPosition + j * magnify, magnify, magnify);
				}
			}

			URL uri = this.getClass().getClassLoader().getResource("plantillas/EtiquetasGrupo/Pictures");
			String s1 = uri.toString().replace("file:", "").replace("%20", " ");
            if (s1.contains(":/")) {
                s1 = s1.substring(1);
            }
            File tempCodigo = new File(s1 + "codigo"+in+".png");
            tempCodigo.delete();
            tempCodigo.createNewFile();
			ImageIO.write(image, "png", tempCodigo);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	public void createQrCode(int width,int heigth) {
		try {
			byte[] b = { 0x48, 0x45, 0x4C, 0x4C, 0x4F };
			// convert the byte array into a UTF-8 string
			String data;
			data = new String(b, "UTF8");

			QRCode qrcode = new QRCode();
			Encoder.encode("http://localhost:8080/Canarios/consultaPajaro.html?id="+puntuacion.getIdPuntuacion(), ErrorCorrectionLevel.L,
					qrcode);

			int qrSize = qrcode.getMatrixWidth();

			int margin = 4;
			int imageSize = qrSize + 2 * margin; // includes quiet zone
			if (width < imageSize)
				width = imageSize;
			int magnify = width / imageSize;
			int remaining = width % imageSize;
			int topLeftPosition = ((remaining > 0) ? remaining / 2 : magnify)
					+ margin * magnify;
			int size = width;

			// Make the BufferedImage that are to hold the QRCode
			BufferedImage image = new BufferedImage(size, size,
					BufferedImage.TYPE_INT_RGB);
			image.createGraphics();
			Graphics2D graphics = (Graphics2D) image.getGraphics();
			graphics.setColor(Color.WHITE);
			graphics.fillRect(0, 0, size, size);

			// paint the image using the ByteMatrix
			graphics.setColor(Color.BLACK);
			for (int i = 0; i < qrSize; i++) {
				for (int j = 0; j < qrSize; j++) {
					if (qrcode.at(i, j) == 1)
						graphics.fillRect(topLeftPosition + i * magnify,
								topLeftPosition + j * magnify, magnify, magnify);
				}
			}

			URL uri = this.getClass().getClassLoader().getResource("plantillas/ETIQUETAS/Pictures");
			String s1 = uri.toString().replace("file:", "").replace("%20", " ");
            if (s1.contains(":/")) {
                s1 = s1.substring(1);
            }
            File tempCodigo = new File(s1 + "codigo.png");
            tempCodigo.delete();
            tempCodigo.createNewFile();
			ImageIO.write(image, "png", tempCodigo);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Concurso getConcurso() {
		return concurso;
	}

	public void setConcurso(Concurso concurso) {
		this.concurso = concurso;
	}

	public Criador getCriador() {
		return criador;
	}

	public void setCriador(Criador criador) {
		this.criador = criador;
	}

	public List<Puntuacion> getListaPajarosIndividual() {
		return listaPajarosIndividual;
	}

	public void setListaPajarosIndividual(
			List<Puntuacion> listaPajarosIndividual) {
		this.listaPajarosIndividual = listaPajarosIndividual;
	}

	public List<PuntuacionGrupo> getListaGrupo() {
		return listaGrupo;
	}

	public void setListaGrupo(List<PuntuacionGrupo> listaGrupo) {
		this.listaGrupo = listaGrupo;
	}

	public Puntuacion getPuntuacion() {
		return puntuacion;
	}

	public void setPuntuacion(Puntuacion puntuacion) {
		this.puntuacion = puntuacion;
	}

	public PuntuacionGrupo getPuntuacionGrupo() {
		return puntuacionGrupo;
	}

	public void setPuntuacionGrupo(PuntuacionGrupo puntuacionGrupo) {
		this.puntuacionGrupo = puntuacionGrupo;
	}

	
	

}
